package com.webchat.ugc.config.shardingJdbc;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

public class CustomHashModShardingAlgorithm implements StandardShardingAlgorithm<String> {

    private Properties props;

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        if (!shardingValue.getLogicTableName().equals("web_chat_moment_timeline")) {
            return shardingValue.getLogicTableName(); // 非目标表直接返回原表
        }

        String user_id = shardingValue.getValue();
        int hash = user_id.hashCode();
        int mod = hash % Integer.parseInt(props.getProperty("sharding-count"));
        // 处理负值
        int index = (mod & 0x7FFFFFFF) % Integer.parseInt(props.getProperty("sharding-count"));
        String suffix = "_" + index;
        return availableTargetNames.stream()
                .filter(table -> table.endsWith(suffix))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("分片路由失败"));
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection,
                                         RangeShardingValue<String> rangeShardingValue) {
        return List.of();
    }

    @Override
    public void init(Properties props) {
        this.props = props;
    }

    @Override
    public String getType() {
        return "CUSTOM_HASH_MOD";
    }
}